package com.songshuai.pangu.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.songshuai.pangu.api.model.es.Article;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import io.searchbox.indices.DeleteIndex;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Api("盘古客户端es接口")
@RequestMapping("/api/es/")
@RestController
public class ESController {


    @Value("${es.indexName}")
    private String indexName;

    @Value("${es.typeName}")
    private String typeName;

    @Autowired
    JestClient jestClient;



    @GetMapping(value = "/add")
    public boolean add(){

        Article article = new Article();
        article.setId("1");
        article.setAuthor("Tom1");
        article.setContent("hello world !");
        article.setTitle("今日消息1");

        Article article2 = new Article();
        article2.setId("2");
        article2.setAuthor("Tom2");
        article2.setContent("hello world2 !");
        article2.setTitle("今日消息2");

        Article article3 = new Article();
        article3.setId("3");
        article3.setAuthor("Tom3");
        article3.setContent("hello world3 !");
        article3.setTitle("今日消息3");

        Bulk bulk = new Bulk.Builder()
                .defaultIndex(indexName)
                .defaultType(typeName)
                .addAction(Arrays.asList(
                        new Index.Builder(article).build(),
                        new Index.Builder(article2).build(),
                        new Index.Builder(article3).build()
                )).build();
        try{
            JestResult result = jestClient.execute(bulk);

            return result.isSucceeded();
        }catch (Exception e){
            e.printStackTrace();
        }

        return false;


    }




    //删除index
    @GetMapping(value = "/deleteIndex")
    public boolean deleteIndex(String indexName) {

        DeleteIndex deleteIndex = new DeleteIndex.Builder(indexName).build();
        try {
            JestResult jestResult = jestClient.execute(deleteIndex);
            return jestResult.isSucceeded();
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    //删除index
    @GetMapping(value = "/searchStr")
    public QueryResponse searchStr(String index) {

        //构建 JSON 字符串
        HashMap<String, Object> query_args = new HashMap<>();
        HashMap<String, Object> match = new HashMap<>();
        HashMap<String, Object> match_all = new HashMap<>();

        //match_all.put("title","今日消息1");
        match.put("match_all", match_all);
        query_args.put("query", match);
        GsonBuilder gsonBuilder = new GsonBuilder();
        String query = gsonBuilder.serializeNulls().create().toJson(query_args);
        //进行RESTful查询
        Search.Builder searchBuilder = new Search.Builder(query).addIndex(indexName).addType(typeName);
        try{
            SearchResult result = jestClient.execute(searchBuilder.build());

            List<Article> list = result.getSourceAsObjectList(Article.class);
            List<SearchResult.Hit<JsonObject, Void>> hits = result.getHits(JsonObject.class);

            int i = 0;
            for(SearchResult.Hit<JsonObject, Void> hit: hits){

                list.get(i).setIdx(hit.id);
                //JsonObject source = hit.source;
                //JsonPrimitive username = source.getAsJsonPrimitive("title");

                //JsonArray tags = source.getAsJsonArray("tags");
                //System.out.println(username);
                //System.out.println(tags);
                i++;
            }
            return QueryResponse.setResData(list);

        } catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 删除单条数据,  这个id必须是主键才能被删除
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/deleteById")
    public boolean deleteById(String id)throws Exception{

        DocumentResult dr = jestClient.execute(new Delete.Builder(id).index(indexName).type(typeName).build());
        return dr.isSucceeded();
    }

    /**
     * 单一查询,  这个id必须是主键才能被删除
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getOne")
    public QueryResponse getOne(String id) throws Exception {
        Get get = new Get.Builder(indexName, id).type(typeName).build();
        JestResult js = jestClient.execute(get);
        JSONObject pa =JSONObject.parseObject(js.getJsonString());

        Article article = js.getSourceAsObject(Article.class);
        article.setIdx(pa.get("_id").toString());
        return QueryResponse.setResData(article);
    }


    /**
     * 更新
     *
     * @param doc 文档
     * @return 是否更新成功
     */

    public boolean update() {

        Article article = new Article();
        article.setId("1");
        article.setAuthor("Tom11111111");
        article.setContent("hello world !");
        article.setTitle("今日消息1");

        try {
            DocumentResult result = jestClient.execute(new Update.Builder(article)
                    .index(indexName)
                    .type(typeName)
                    .refresh(true)
                    .build());
            return result.isSucceeded();
        } catch (Exception e) {
            throw new RuntimeException("update exception", e);
        }
    }




}
